package workers;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.SwingWorker;

import messaging.IMessagingHandler;
import model.Software;
import workerUIs.StepFrame;

/**
 * Abstract Swing Worker class.
 * 
 * @author Mark Czotter
 * @author Miklos Szennai
 * 
 */
public abstract class AbstractStepSwingWorker extends
		SwingWorker<Software, Void> {
	
	protected Logger logger = Logger.getLogger(AbstractStepSwingWorker.class.getCanonicalName());
	
	protected final StepFrame frame;
	protected final IMessagingHandler<Software> messagingHandler;
	
	protected Software software;

	public AbstractStepSwingWorker(final StepFrame frame, IMessagingHandler<Software> messagingHandler) {
		this.frame = frame;
		this.messagingHandler = messagingHandler;
	}

	@Override
	protected Software doInBackground() throws Exception {
		try {
			this.software = this.messagingHandler.get();
			if (this.software != null) {
				doStep(this.software);
				this.messagingHandler.put(this.software);
			}
			return this.software;
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Exception when executing step: " + getClass().getName() + ": " + e.getMessage());
		}
		return null;
	}

	protected abstract void doStep(Software software);
	
	@Override
	protected void done() {
		String previousStepString = this.frame.getTextArea().getText() + "\n--------------\n";
		if (this.software != null) {
			this.frame.getTextArea().setText(previousStepString + this.software.toString());
		} else {
			this.frame.getTextArea().setText(previousStepString + "Software NULL!");
		}
	}
	
	public StepFrame getFrame() {
		return this.frame;
	}
	
}
